// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
 * @fileoverview A dialog to confirm key imports.
 */

goog.provide('e2e.ext.ui.dialogs.ImportConfirmation');

goog.require('e2e.ext.constants.CssClass');
goog.require('e2e.ext.ui.dialogs.Generic');
goog.require('e2e.ext.ui.dialogs.InputType');
goog.require('e2e.ext.ui.templates.dialogs.importconfirmation');
goog.require('goog.array');
goog.require('goog.events.EventType');
goog.require('goog.string.format');

goog.scope(function() {
var ui = e2e.ext.ui;
var constants = e2e.ext.constants;
var dialogs = e2e.ext.ui.dialogs;
var templates = e2e.ext.ui.templates.dialogs.importconfirmation;



/**
 * Constructor for the import confirmation dialog.
 * @param {!e2e.openpgp.Keys} keys The keys to import.
 * @param {!function(string=)} callback The callback where the user's
 *     input must be passed.
 * @constructor
 * @extends {dialogs.Generic}
 */
dialogs.ImportConfirmation = function(keys, callback) {
  goog.base(
      this,
      templates.importKeyConfirm({
        promptImportKeyConfirmLabel: chrome.i18n.getMessage(
            'promptImportKeyConfirmLabel'),
        selectAllLabel: chrome.i18n.getMessage('dialogSelectAll'),
        keys: keys,
        secretKeyDescription: chrome.i18n.getMessage('secretKeyDescription'),
        publicKeyDescription: chrome.i18n.getMessage('publicKeyDescription'),
        secretSubKeyDescription: chrome.i18n.getMessage(
            'secretSubKeyDescription'),
        publicSubKeyDescription: chrome.i18n.getMessage(
            'publicSubKeyDescription')
      }),
      callback,
      dialogs.InputType.NONE,
      '',
      chrome.i18n.getMessage('promptOkActionLabel'),
      chrome.i18n.getMessage('actionCancelPgpAction'));
};
goog.inherits(dialogs.ImportConfirmation, dialogs.Generic);


/** @override */
dialogs.ImportConfirmation.prototype.enterDocument = function() {
  goog.base(this, 'enterDocument');

  this.getHandler().listen(
      this.getElement(),
      goog.events.EventType.CHANGE,
      this.handleSelect_,
      true);

  this.getHandler().listen(
      this.getElementByClass(constants.CssClass.SELECT_ALL_LINK),
      goog.events.EventType.CLICK,
      this.selectAll_);
};


/**
 * Handles events when the user selects/unselects a key to import.
 * @param {!goog.events.Event} changeEvt The event generated by the user
 *     selecting/unselecting a key.
 * @private
 */
dialogs.ImportConfirmation.prototype.handleSelect_ = function(changeEvt) {
  var checkbox = /** @type (HTMLInputElement) */ (changeEvt.target);

  if (!goog.isDef(checkbox.id)) {
    // Not an element we're interested in.
    return;
  }

  if (checkbox.checked && checkbox.hasAttribute('data-subkey')) {
    // If a subkey is selected, make sure that the parent key is also selected.
    var parentKeySelector = goog.string.format(
        'input[data-mainkey="%s"]:not([data-subkey])',
        checkbox.getAttribute('data-mainkey'));
    var parentCheckbox = this.getElement().querySelector(parentKeySelector);
    parentCheckbox.checked = true;
  }

  if (!checkbox.checked && !checkbox.hasAttribute('data-subkey')) {
    var selector = goog.string.format(
        'input[data-mainkey="%s"]', checkbox.getAttribute('data-mainkey'));
    goog.array.forEach(
        this.getElement().querySelectorAll(selector), function(child) {
          child.checked = false;
        });
  }
};


/**
 * Selects all keys in the dialog.
 * @private
 */
dialogs.ImportConfirmation.prototype.selectAll_ = function() {
  goog.array.forEach(
      this.getElement().querySelectorAll('input[data-mainkey]'),
      function(checkbox) {
        checkbox.checked = true;
      });
};


/** @override */
dialogs.ImportConfirmation.prototype.invokeCallback = function(sendBlank) {
  var verifiedAll = goog.array.every(
      this.getElement().querySelectorAll('input[data-mainkey]'),
      function(checkbox) {
        return checkbox.checked;
      });
  if (!sendBlank && !verifiedAll) {
    window.alert(chrome.i18n.getMessage('promptImportKeyVerifyLabel'));
    return;
  }

  goog.base(this, 'invokeCallback', sendBlank);
};

}); // goog.scope
